//
//  AccountMyQuestionVC.m
//  ImGuider
//
//  Created by llt on 2017/8/24.
//  Copyright © 2017年 AudioCtrip. All rights reserved.
//

#import "AccountMyQuestionVC.h"
#import "AccountQuestionCell.h"

#import "LinePreDetailVC.h"

@interface AccountMyQuestionVC ()
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonatomic, strong) AccountQuestionCell *currentCell;
@property (nonatomic, strong) Question *cquestion;

@end

@implementation AccountMyQuestionVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setup];
}

- (void)viewDidDisappear:(BOOL)animated {
    
    [super viewDidDisappear:animated];
    
    [[PlayerManager shareManeger] stop];
}

- (void)setup {
    
    self.title = MYLocalizedString(@"ACCOUNT_MY_QUESTION", nil);
    
    [self configEmptyDataTableView:self.tableView emptyImageName:@"暂无提问" describe:MYLocalizedString(@"MYQUESTION_NO_QUESTION", nil) refresh:nil block:nil];
    
    
    self.tableView.estimatedRowHeight = 44;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    
    [ActivityIndicatorView showHUDAddedTo:self.view];
    [self loadNewData];
    
    @weakify(self);
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self);
        
        [self loadNewData];
    }];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeAudioState:) name:kPlayManagerState object:nil];
    [self.tableView setThemeStyle:ThemeStyleBlack];
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)loadNewData {
    
    @weakify(self);
    [NetAPIManager getMyQuestionBlock:^(NSArray<Question *> *questionArray, NSError *error) {
        @strongify(self);
        [ActivityIndicatorView hideHUDAddedTo:self.view];
        [self.tableView.mj_header endRefreshing];
        
        self.dataHasLoad = YES;

        self.dataSource = [NSMutableArray arrayWithArray:questionArray];

        [self.tableView reloadData];
        
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            NSInteger unread = 0;
            
            for (Question *question in questionArray) {
                
                if (question.status.integerValue == 3 && question.isread.boolValue != YES) {
                    unread ++;
                }
            }
            
            [UserManager sharedManager].user.unread = @(unread).stringValue;
            
            dispatch_async(dispatch_get_main_queue(), ^ {
                [[NSNotificationCenter defaultCenter] postNotificationName:kRefreshUserNotif object:nil];
            });
        });
        
    }];
}


- (void)changeAudioState:(NSNotification *)notif {
    
    NSInteger state = [notif.userInfo[kPlayManagerState] integerValue];
    NSString  *url = notif.userInfo[kCurrentPlayURL];
    
    if (![url isEqualToString:self.cquestion.answer]) {
        return;
    }
    
    switch (state) {
        case AVPlayerPlayStatePause:
        case AVPlayerPlayStateEnd:
        {
            [self.currentCell stopPlay];
            self.cquestion = nil;
            self.currentCell = nil;
            
        }
            break;
    }
}


#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    AccountQuestionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AccountQuestionCell"];
    
    Question *question = self.dataSource[indexPath.row];
    cell.delegate = self;
    cell.superVC = self;
    
    cell.question = question;
    
    if ([self.cquestion.qid isEqualToString:question.qid]) {
        [cell startPlay];
    } else {
        [cell stopPlay];
    }
    
    return cell;
}

#pragma mark - AccountQuestionCellDelegate

- (void)lineNameTapped:(AccountQuestionCell *)cell question:(Question *)question {
    
//    LineModel *model = [LineModel new];
//    model.linename = question.title;
//    model.lineid = question.lineid;
    
    LinePreDetailVC *preDetailVC = [IGUtils loadViewController:@"LinePreDetailVC" storyboard:@"LineDetail"];
    preDetailVC.lineid = question.lineid;
    [self.navigationController pushViewController:preDetailVC animated:YES];
}

- (void)answerAudioTapped:(AccountQuestionCell *)cell question:(Question *)question {
    
    if ([question.qid isEqualToString:self.cquestion.qid]) {
        [[PlayerManager shareManeger] pause];
        return;
    }
    
    if ([[PlayerManager shareManeger].currentURL isEqualToString:question.answer]) {
        [[PlayerManager shareManeger] play];
    } else {
        
        if ([[PlayerManager shareManeger].currentURL isEqualToString:self.cquestion.answer]) {
            [self.currentCell stopPlay];
        }
        
        [[PlayerManager shareManeger] playMusic:question.answer withIsPlay:YES];
    }
    [NetAPIManager clickCountWithID:question.qid type:@(3).stringValue];
    self.currentCell = cell;
    self.cquestion = question;
    [cell startPlay];
    
    
    if (!question.isread.boolValue) {
        [NetAPIManager setMessgaeReadWithQid:question.qid Block:^(NSString *result, NSError *error) {
            
            if (!error) {
                question.isread = @"1";
                
                cell.question = question;
                
                NSInteger unreadCount = [UserManager sharedManager].user.unread.integerValue;
                
                unreadCount -= 1;
                
                if (unreadCount < 0) {
                    unreadCount = 0;
                }
                
                [UserManager sharedManager].user.unread = @(unreadCount).stringValue;
                
                [[NSNotificationCenter defaultCenter] postNotificationName:kRefreshUserNotif object:nil];
            }
        }];
    }
}

@end
